package com.feng.shiro.config;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.shiro.bean.User;
import com.feng.shiro.service.UserService;
import com.feng.shiro.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.LinkedHashMap;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userservice;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(user.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证方法");

        //账号密码数据库中取...
//        String name = "admin";
//        String password = "123456";

        UsernamePasswordToken userToken = (UsernamePasswordToken)token;

        //账号验证
        User user = userservice.queryUserByName(userToken.getUsername());
        if (user==null){
            return null;
        }

        //密码认证，shiro做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
